<template>
  <!-- 自习室预约管理界面 -->
  <div class="margin-top">
    <!-- 搜索框 -->
    <el-input v-model="searchValue" placeholder="请输入自习室名或设施关键词"
              style="width: 300px; margin-bottom: 10px;"></el-input>
    <el-button type="primary" size="small" @click="searchRoom">搜索自习室</el-button>

    <!-- 自习室列表 -->
    <el-table :data="filteredRooms" style="width: 100%">
      <!-- 自习室表格列 -->
      <el-table-column prop="roomName" label="自习室名称"></el-table-column>
      <el-table-column prop="facilities" label="自习室设施"></el-table-column>
      <el-table-column prop="capacity" label="剩余座位"></el-table-column>
      <el-table-column label="操作">
        <!-- 操作列，预约按钮 -->
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="reserveRoom(scope.row)">预约</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 预约对话框 -->
    <el-dialog title="预约自习室" :visible.sync="reserveDialogVisible" width="30%">
      <!-- 预约表单 -->
      <el-form :model="reserveForm" label-width="100px">
        <el-form-item label="开始时间">
          <el-date-picker v-model="reserveForm.startTime" type="datetime"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker v-model="reserveForm.endTime" type="datetime"></el-date-picker>
        </el-form-item>
        <el-form-item v-if="timeError" label="错误信息">
          <span style="color: red;">{{ timeError }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reserveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReserve">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data () {
    return {
      searchValue: '', // 搜索关键词
      rooms: [], // 自习室列表
      reserveDialogVisible: false, // 预约对话框显示状态
      reserveForm: {
        roomName: '', // 自习室名称
        name: '', // 用户名
        startTime: null, // 开始时间
        endTime: null, // 结束时间
        reserveStatus: '' // 预约状态
      },
      timeError: '' // 错误信息
    }
  },
  computed: {
    filteredRooms () {
      // 根据关键词过滤自习室列表
      const keyword = this.searchValue.toLowerCase().trim()
      return this.rooms.filter(room =>
          room.roomName.toLowerCase().includes(keyword) ||
          room.facilities.toLowerCase().includes(keyword)
      )
    }
  },
  created () {
    // 初始化时获取自习室列表
    this.fetchRooms()
  },
  methods: {
    // 更新自习室剩余座位数量
    async updateRoomCapacity (roomName, capacity) {
      try {
        const data = {
          roomName: roomName,
          capacity: capacity
        }
        await axios.put(`http://localhost:7070/api/user/updatecapacity/${roomName}`, data)
      } catch (error) {
        console.error('更新自习室座位数量失败:', error)
      }
    },
    // 获取自习室列表
    async fetchRooms () {
      try {
        const response = await axios.get('http://localhost:7070/api/user/allstudyroom')
        this.rooms = response.data
      } catch (error) {
        console.error('获取自习室列表失败:', error)
      }
    },
    // 搜索自习室
    searchRoom () {
      console.log('搜索自习室：', this.searchValue)
    },
    // 预约自习室
    reserveRoom (row) {
      // 填充预约表单信息
      this.reserveForm.roomName = row.roomName // 自习室名称
      this.reserveForm.name = localStorage.getItem('uname') // 用户名
      this.reserveForm.reserveStatus = '待审核' // 预约状态
      this.reserveDialogVisible = true
    },
    // 确认预约操作
    async confirmReserve () {
      const {
        startTime,
        endTime,
        roomName
      } = this.reserveForm

      // 获取当前时间
      const currentTime = new Date()

      if (!startTime || !endTime) {
        this.timeError = '请选择开始时间和结束时间'
        return
      }
      if (startTime >= endTime) {
        this.timeError = '结束时间必须晚于开始时间'
        return
      }
      if (startTime <= currentTime || endTime <= currentTime) {
        this.timeError = '开始时间和结束时间必须晚于当前时间'
        return
      }

      this.timeError = '' // 清空错误信息

      // 手动增加一天到开始时间和结束时间
      const newStartTime = new Date(startTime)
      newStartTime.setDate(newStartTime.getDate() + 1)
      this.reserveForm.startTime = newStartTime

      const newEndTime = new Date(endTime)
      newEndTime.setDate(newEndTime.getDate() + 1)
      this.reserveForm.endTime = newEndTime

      // 查找目标自习室在当前页面数据中的索引
      const targetRoomIndex = this.rooms.findIndex(room => room.roomName === roomName)
      if (targetRoomIndex === -1) {
        console.error('未找到目标自习室:', roomName)
        this.$message.error('预约失败，自习室不存在')
        return
      }

      const targetRoom = this.rooms[targetRoomIndex]
      if (targetRoom.capacity <= 0) {
        this.$message.error('座位已满，预约失败')
        return
      }

      // 发送预约请求
      try {
        await axios.post('http://localhost:7070/api/user/reserve', this.reserveForm)
        this.$message.success('预约成功')

        // 更新自习室剩余座位数量
        targetRoom.capacity-- // 扣减座位数量
        await this.updateRoomCapacity(roomName, targetRoom.capacity)

        // 更新视图
        this.$set(this.rooms, targetRoomIndex, targetRoom)
        this.reserveDialogVisible = false
      } catch (error) {
        console.error('预约失败:', error)
        this.$message.error('预约失败，请稍后重试')
      }
    }
  }
}
</script>

<style scoped>
.margin-top {
  margin-top: 20px;
}
</style>
